/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projetluc;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Lone_Wolf
 */
public class ConsulterClient extends JPanel {

    private Fenetre fenetre;
    private Entree dernEntreeSelect;
    private Client client;
    Font f = new Font("Times New Roman", Font.BOLD, 24);
    private ArrayList<SearchResult> entrees;
    private GridBagLayout gbl;
    private GridBagConstraints gbc;
    private JLabel lblNom;
    private JLabel lblCode;
    private JLabel lblPage;
    private JButton btnCreer;
    private JButton btnPageSuiv;
    private JButton btnPagePrec;
    private JButton btnAnnuler;
    private JButton btnModifierClient;
    private JButton btnModifierEntree;
    private JButton btnStats;
    private Facture facture;
    private int pageCourante;
    private int nbeEntreesTotal;
    private int nbeEntreesParPage = 10;
    private StatsClient stats;

    public ConsulterClient(Fenetre fenetre, Client client) {
        this.fenetre = fenetre;
        this.client = client;
        
        dernEntreeSelect = null;

        this.fenetre.setSize(510, 510);
        this.fenetre.setTitle("Consulter " + client.getNom());
        this.fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        pageCourante = 1;
        facture = new Facture(client);

        executerRecherches();
        initComposants();
        buildInterface();

        this.fenetre.setVisible(true);
    }

    private void initComposants() {
        lblNom = new JLabel(client.getNom());
        lblCode = new JLabel(client.getCode());
        lblNom.setFont(f);
        lblCode.setFont(f);
        lblPage = new JLabel(calculPage());

        btnCreer = new JButton("Créer Facture");
        btnAnnuler = new JButton("Retour");
        btnModifierClient = new JButton("Modifier Client");
        btnModifierEntree = new JButton("Modifier Entrée");
        btnPageSuiv = new JButton("Page Suivante");
        btnPagePrec = new JButton("Page Précédente");
        btnStats = new JButton("Statistiques");

        btnPagePrec.addActionListener(new GererEvenements());
        btnPageSuiv.addActionListener(new GererEvenements());
        btnCreer.addActionListener(new GererEvenements());
        btnAnnuler.addActionListener(new GererEvenements());
        btnModifierClient.addActionListener(new GererEvenements());
        btnModifierEntree.addActionListener(new GererEvenements());
        btnStats.addActionListener(new GererEvenements());
    }

    private String calculPage() {
        String temp = "Page " + pageCourante + "/";
        if (nbeEntreesTotal == 0) {
            temp = temp + "1";
        } else if (nbeEntreesTotal % nbeEntreesParPage == 0) {
            temp = temp + ((nbeEntreesTotal / nbeEntreesParPage));
        } else {
            temp = temp + ((nbeEntreesTotal / nbeEntreesParPage) + 1);
        }

        return temp;
    }

    private void buildInterface() {
        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();
        this.setLayout(gbl);
        gbc.fill = GridBagConstraints.BOTH;

        makeSeparator();
        makeBorder();
        gbc.weightx = 0.0;                          //Nom et Code
        gbl.setConstraints(lblNom, gbc);
        this.add(lblNom);
        makeBorder();
        gbc.weightx = 0.0;
        gbl.setConstraints(lblCode, gbc);
        this.add(lblCode);
        makeBorder();
        gbc.weightx = 0.1;
        gbc.fill = gbc.NONE;
        gbc.anchor = gbc.LINE_END;
        gbl.setConstraints(btnModifierClient, gbc);
        this.add(btnModifierClient);
        gbc.gridwidth = gbc.REMAINDER;
        makeBorder();
        makeSeparator();
        makeSeparator();

        buildResults();                         //Résultats

        makeSeparator();
        makeBorder();
        gbc.weightx = 0.1;                      //Page suiv/prec
        gbc.fill = gbc.NONE;
        gbc.anchor = gbc.LINE_START;
        gbl.setConstraints(btnPagePrec, gbc);
        this.add(btnPagePrec);
        makeBorder();
        gbc.weightx = 0.1;
        gbc.anchor = gbc.CENTER;
        gbl.setConstraints(lblPage, gbc);
        this.add(lblPage);
        gbc.weightx = 0.1;
        gbc.fill = gbc.NONE;
        gbc.anchor = gbc.LINE_END;
        gbc.gridwidth = gbc.RELATIVE;
        gbl.setConstraints(btnPageSuiv, gbc);
        this.add(btnPageSuiv);
        makeBorder();

        makeSeparator();                        //Boutons
        makeSeparator();
        makeSeparator();
        makeSeparator();
        makeBorder();
        gbc.weightx = 0.1;
        gbc.fill = gbc.NONE;
        gbc.anchor = gbc.LINE_START;
        gbl.setConstraints(btnAnnuler, gbc);
        this.add(btnAnnuler);
        makeBorder();
        gbc.anchor = gbc.CENTER;
        gbl.setConstraints(btnModifierEntree, gbc);
        this.add(btnModifierEntree);
        makeBorder();
        gbc.gridwidth = gbc.RELATIVE;
        gbc.anchor = gbc.LINE_END;
        gbl.setConstraints(btnCreer, gbc);
        this.add(btnCreer);
        makeBorder();
        makeSeparator();
        makeSeparator();
        
        //bouton stats
        gbc.gridwidth = gbc.RELATIVE;
        gbc.anchor = gbc.LINE_END;
        gbl.setConstraints(btnStats, gbc);
        this.add(btnStats);
        makeBorder();
    }

    private void executerRecherches() {
        boolean[] params = new boolean[7];
        params[3] = true;
        entrees = new Search(fenetre, client.getCode(), params).getArrResultats2();

        //remove entrees facturees
        for (int i = 0; i < entrees.size(); i++) {
            if (entrees.get(i).getEntree().getFacturee()) {
                entrees.remove(i);
                i--;
                System.out.println(entrees.get(i).getEntree().getYear());
            }
        }

        nbeEntreesTotal = entrees.size();
        calculStats();
    }
    
    private void calculStats(){
        stats = new StatsClient(fenetre, client);
        Entree temp;
        for(int i = 0; i < entrees.size();i++){
            temp = entrees.get(i).getEntree();
            stats.addStat(temp);
        }
    }

    private void buildResults() {
        int debut = (pageCourante - 1) * nbeEntreesParPage;
        int fin = debut + nbeEntreesParPage;

        for (int i = debut; i < entrees.size() && debut < fin; i++) {
            if (entrees.get(i).getEntree().getFacturee() == false) {
                makeBorder();
                gbc.weightx = 0.1;
                gbc.fill = gbc.HORIZONTAL;
                gbc.gridwidth = gbc.RELATIVE;
                gbl.setConstraints(entrees.get(i), gbc);
                ((SearchResult) entrees.get(i)).addActionListener(new GererActionsRecherche());
                dejaSelectionne((SearchResult) entrees.get(i));
                this.add(entrees.get(i));
                gbc.gridwidth = gbc.REMAINDER;
                makeBorder();

                debut++;
            } else {
            }
        }
    }

    private void makeSeparator() {
        JLabel sep = new JLabel(" ");
        gbc.gridwidth = gbc.REMAINDER;
        gbl.setConstraints(sep, gbc);
        this.add(sep);
        gbc.gridwidth = gbc.CENTER;
        gbc.weighty = 0;
    }

    private void makeBorder() {
        gbc.weightx = 0.0;
        JLabel sep = new JLabel("   ");
        gbl.setConstraints(sep, gbc);
        this.add(sep);
        gbc.gridwidth = gbc.CENTER;
    }

    private void updatePage() {
        //lblPage.setText("Page " + pageCourante + "/" + ((nbeEntreesTotal / nbeEntreesParPage) + 1));
        this.removeAll();
        this.invalidate();
        this.repaint();
        executerRecherches();
        initComposants();
        buildInterface();
        this.invalidate();
        this.revalidate();
        this.repaint();
    }

    private void dejaSelectionne(SearchResult sr) {
        if (facture.contientEntree(sr.getEntree())) {
            sr.setForeground(Color.red);
        }
    }

    private boolean creerFacture() {
        boolean facture_cree = false;
        String numeroFacture = "";
        boolean numeroInvalide = false;
        String reponse;
        double cout = 0;

        //on demande le numero de la facture
        do {
            reponse = new String();
            reponse = JOptionPane.showInputDialog(fenetre,
                    "Entrer le numéro de la facture à créer", "Numéro de facture", JOptionPane.QUESTION_MESSAGE);
            if (reponse == null) {
                numeroInvalide = false;
            } else {
                try {
                    numeroFacture = reponse;
                    if (numeroFacture.isEmpty()) {
                        numeroInvalide = true;
                    }
                } catch (Exception e) {
                }
                for (int i = 0; i < fenetre.arFactures.size(); i++) {
                    if ((numeroFacture).equals(((Facture) fenetre.arFactures.get(i)).getNumero())) {
                        JOptionPane.showConfirmDialog(fenetre, "Ce numéro de facture existe déjà", "Facture invalide", JOptionPane.WARNING_MESSAGE);
                        i = fenetre.arFactures.size();
                        numeroInvalide = true;
                    }
                }
            }
        } while (numeroInvalide);


        //on demande ce qu'on veut charger au client
        if (reponse != null) {
            do {
                reponse = new String();
                reponse = JOptionPane.showInputDialog(fenetre,
                        "Entrer le montant que vous voulez charger au client.\n"
                        + "D'après le calcul des salaires, la facture s'élève à: " + facture.getCoutTotal() + "$", "Montant à charger", JOptionPane.QUESTION_MESSAGE);
                if (reponse == null) {
                    numeroInvalide = false;
                    return (false);
                } else {
                    try {
                        cout = Double.parseDouble(reponse);
                    } catch (Exception e) {
                    }
                }
            } while (cout <= 0);
        }

        //toutes les valeurs sont valides, on cree la facture + ajout dans la BD
        if (reponse != null) {
            facture.setNumero(numeroFacture);
            facture.setMontantCharge(cout);
            facture.finaliser();
            fenetre.arFactures.add(facture);
            try {
                fenetre.sauvegarderBD();
                facture_cree = true;
            } catch (IOException ex) {
                Logger.getLogger(ConsulterClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return (facture_cree);
    }

    class GererEvenements implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == btnCreer) {
                if (facture.getNbeEntrees() > 0) {
                    if (creerFacture()) {
                        try {
                            fenetre.AfficherEcranRecherche();
                        } catch (IOException ex) {
                            Logger.getLogger(ConsulterClient.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ClassNotFoundException ex) {
                            Logger.getLogger(ConsulterClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            } else if (e.getSource() == btnAnnuler) {
                try {
                    fenetre.AfficherEcranRecherche();
                } catch (IOException ex) {
                    Logger.getLogger(CreerNouvEmploye.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(CreerNouvEmploye.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (e.getSource() == btnModifierClient) {
                fenetre.afficherModifierClient(client);
            } else if (e.getSource() == btnModifierEntree) {
                if (dernEntreeSelect != null) {
                    fenetre.afficherModifierEntree(dernEntreeSelect);
                }
            } else if (e.getSource() == btnPageSuiv) {
                if (pageCourante * nbeEntreesParPage < nbeEntreesTotal) {
                    pageCourante++;
                    updatePage();
                }
            } else if (e.getSource() == btnPagePrec) {
                if (pageCourante > 1) {
                    pageCourante--;
                    updatePage();
                }
            } else if (e.getSource() == btnStats){
                fenetre.afficherStatsClient(stats);
            }
        }
    }

    class GererActionsRecherche implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            SearchResult srTemp = (SearchResult) e.getSource();
            dernEntreeSelect = srTemp.getEntree();
            
            if (srTemp.getForeground() == Color.red) {
                srTemp.setForeground(Color.darkGray);
                facture.removeEntree(srTemp.getEntree());
            } else {
                srTemp.setForeground(Color.red);
                facture.addEntree(srTemp.getEntree());
            }
        }
    }
}
